export default class Emitter {
    constructor() {
        if (Emitter.instance) {
            return Emitter.instance;
        }
        Emitter.instance = this;

        this._events = {};
        this.params = null;
        this.locked = false;
    }

    on(event, cb) {
        const query = this._events[event] || [];
        query.push(cb);
        this._events[event] = query;
        return this;
    }

    off(event, cb) {
        const query = this._events[event];
        this._events[event] = query && query.filter(fn => fn !== cb);
        return this;
    }

    emit(...args) {
        const query = this._events[args[0]];
        const params = Array.prototype.slice.call(args, 1);
        this.params = params;

        query.forEach(fn => {
            fn.call(params)
        })

        return this;
    }

    once(event, cb) {
        const wrapperFun = (...args) => {
            cb.apply(this, args);
            this.off(event, wrapperFun);
        }
        this.on(event, wrapperFun);
        return this;
    }
}
